/*
 * TransactionDAO.java
 *
 * Created on February 18, 2007, 8:31 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.samlam;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Sam
 */
public class TransactionDAO {
    ///////////////////////////////////////
    ///   Singleton pattern
    
    private static TransactionDAO instance;
    
    /** Creates a new instance of TransactionDAO */
    public TransactionDAO() {
    }
    
    public static synchronized TransactionDAO getInstance() {
        if (instance == null) {
            instance = new TransactionDAO();
        }
        return instance;
    }
    
    /////////////////////////////////
    ///   CREATE
    
    /**
     * There's no need for two creates because we don't need
     * a connection to create BOs.  We run the insert statement
     * later, when it get's saved for the first time.
     */
    public Transaction create() {
        Transaction t = null;
        try{
            String id = GUID.generate();
            t = new Transaction(id);
            long time = System.currentTimeMillis();
            t.setDate(time);
            t.setStatus("pending");
            Cache cache = Cache.getInstance();
            cache.put(t.getId(), t);
            
        }catch(Exception e){
            e.printStackTrace();
        }
        return t;
    }
    
    
    /////////////////////////////////////
    ///   READ
    
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized Transaction read(String id) throws DataException {
        // check to see if id in the cache
        Transaction t = (Transaction)Cache.getInstance().get(id);
        if(t != null){
            // if so, return it immediately
            return t;
        }
        
        
        
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call read with a connection (the other read method in this class)
            t = TransactionDAO.getInstance().read(id, conn);
            
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
            
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
            
        }catch (SQLException e) {
            // rollback
            try{
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch(SQLException e2){
                throw new DataException("Big error: could not even release the connection", e2);
            }catch (ConnectionPoolException e3){
                throw new DataException("Could not get a connection to the database.");
                
            }
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // return object
        return t;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    synchronized Transaction read(String id, Connection conn) throws SQLException, DataException {
        // check again if the id is in the cache, and if so,
        // just get it from the cache.  we need to check again
        // because this method might be called directly from
        // another DAO rather than from read above.
        Transaction transaction = (Transaction)Cache.getInstance().get(id);
        if(transaction != null){
            return transaction;
        }
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM trans WHERE transactionid = '"+ id + "'");
        
        //create a prepared statement
        //query the database
        //call sets from the result set
        Transaction t;
        if (rs.next()) {
            t = new Transaction(rs.getString("transactionid"));
            
            t.setCustomer(CustomerDAO.getInstance().read(rs.getString("custid"), conn));
            t.setTxLinesList(TransactionLineDAO.getInstance().readByTransactionId(rs.getString("transactionid"), conn));
            //t.setPayment(PaymentDAO.getInstance().readByTransactionId(rs.getString("transactionid"), conn));
            t.setType(rs.getString("type"));
            t.setStatus(rs.getString("status"));
            t.setEmployee(EmployeeDAO.getInstance().read(rs.getString("employeeid"), conn));
            t.setDate(rs.getLong("date"));
            t.setStore(StoreDAO.getInstance().read(rs.getString("storeid"),conn));

            
            // get any subobjects (for example, if this was the TransactionDAO,
            // we'd need to call the MembershipDAO to load the membership record.
            
            t.setObjectAlreadyInDB(true);
            
            
            // save to the cache
            
            Cache.getInstance().put(t.getId(), t);
            stmt.close();
        }else{
            throw new DataException("Object was not found in the database.");
            
        }
        // return the BO
        return t;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     */
    public synchronized void save(Transaction t) throws DataException {
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call save with a connection (the other save method in this class)
            this.save(t, conn);
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve record for id=" + t.getId(), e);
        }
    }
    
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the TransactionDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     */
    synchronized void save(Transaction t, Connection conn) throws SQLException, DataException {
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (t.isDirty()) {
            
            if (t.isObjectAlreadyInDB() == true) {
                update(t, conn);
            }else{
                insert(t, conn);
            }
            // set the dirty flag to false now that we've saved it
            t.setDirty(false);
            
        }
        
        // call save(bo, conn) on any subobjects (like TransactionDAO to MembershipDAO)
        
        // here I iterate through the transaction lines and save them one by one
        for(int i = 0; i<t.getTxLinesList().size(); i++){
           TransactionLineDAO.getInstance().save(t.getTxLinesList().get(i), conn);
        }
        
        //here I save the payment
        PaymentDAO.getInstance().save(t.getPayment(), conn);
        
        //save payment
        // save payment
        // not saving customer, session, store, or employee because the values of these objects
        // should never change
        // touch the cache for the object
        Cache.getInstance().touch(t.getId());
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(Transaction transaction, Connection conn) throws SQLException, DataException {
        // do the update statement
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("UPDATE trans set transactionid='"+transaction.getId()+"', custID='"+transaction.getCustomer().getId()+"', SubTotal='"+transaction.getSubtotal()+"', Total='"+transaction.getTotal() +"', Tax='"+transaction.getTax()+"', Date='"+transaction.getDate()+"', Type='"+ transaction.getType() +"', Status='"+transaction.getStatus()+"', employeeID='"+transaction.getEmployee().getId()+"' WHERE transactionid='"+transaction.getId()+"'");
        stmt.close();
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(Transaction transaction, Connection conn) throws SQLException, DataException {
        // do the insert SQL statement
        Statement stmt = conn.createStatement();
        
        stmt.executeUpdate("INSERT INTO trans  VALUES ('"+transaction.getId()+"', '"+transaction.getCustomer().getId()+"', '"+transaction.getSubtotal()+"', '"+transaction.getTotal()+"', '"+transaction.getTax()+"', '"+transaction.getDate()+"', '"+transaction.getType()+"', '"+transaction.getStatus()+"', '"+transaction.getEmployee().getId()+"'");
        stmt.close();
        // tell the object that it's now in the db (so we call update next time not insert)
        transaction.setObjectAlreadyInDB(true);
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    // we are not supporting because we never want to delete the transaction from
    // our database.
    
    
    
    //////////////////////////////
    ///  SEARCH methods
    
    public List<String[]> getAll() throws DataException {
        LinkedList<String[]> allList = new LinkedList();
        // get the connection
        
        Connection conn = null;
        try{
            
            conn = ConnectionPool.getInstance().get();
            
            // sql the names, phone, and ids
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customer_id, first_name, last_name, phone FROM transaction");
            
            // while loop to populate the list from the results
            while(rs.next()) {
                String[] jimmy = {rs.getString("customer_id"), rs.getString("first_name"), rs.getString("last_name"), rs.getString("phone")};
                allList.add(jimmy);
            }
            stmt.close();
            // release my connection
            ConnectionPool.getInstance().release(conn);
            // return the list
            return allList;
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve any transaction records", e);
        }
        
    }
    
    public List<Transaction> getByName(String fname, String lname) throws DataException {
        List<Transaction> custList = new LinkedList();
        // get the connection
        
        Connection conn = null;
        try{
            
            conn = ConnectionPool.getInstance().get();
            
            // sql the transaction
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customer_id FROM transaction WHERE '"+fname+"'=first_name AND '"+lname+"'=last_name");
            
            // while loop to populate the list from the results
            while(rs.next()) {
                String custId = rs.getString("customer_id");
                Transaction transaction = this.read(custId, conn);
                custList.add(transaction);
            }
            stmt.close();
            // release my connection
            ConnectionPool.getInstance().release(conn);
            // return the list
            return custList;
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve any transaction records", e);
        }
        
    }
    
    public List<Transaction> getByPhone(String phoneNumber) throws DataException {
        LinkedList<Transaction> custList = null;
        // get the connection
        
        Connection conn = null;
        try{
            
            conn = ConnectionPool.getInstance().get();
            
            // sql the transaction using phoneNumber
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customer_Id FROM transaction WHERE '"+phoneNumber+"'= phone");
            
            // while loop to populate the list from the results
            while(rs.next()) {
                String custId = rs.getString("customerid");
                Transaction transaction = this.read(custId, conn);
                custList.add(transaction);
            }
            // release my connection
            stmt.close();
            ConnectionPool.getInstance().release(conn);
            // return the list
            return custList;
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve any transaction records", e);
        }
        
    }
    
}
